package com.crayon2f.test;

import com.google.common.collect.Lists;
import jodd.util.StringUtil;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.junit.Test;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by feifan.gou@gmail.com on 2024/4/15 19:51.
 */
public class KindleSolveIndex {

    private static final String INDEX_PATH = "D:\\download\\kindle-html\\text";
    private static final String MAIN_TITLE_CLASS = "title";
    private static final String SUB_TITLE_CLASS = "title1";

    @Test
    @SneakyThrows
    public void index() {

        Path path = Paths.get(INDEX_PATH);
        List<String> titleStrList = Lists.newArrayList();
        Files.list(path).forEach(html -> {
            try {
                String htmlStr = String.join(StringUtils.EMPTY, Files.readAllLines(html));
                Document document = Jsoup.parse(htmlStr);
                Element mainTitle = document.getElementsByClass(MAIN_TITLE_CLASS).get(0);
                String id = mainTitle.attr("id");
                String filename = html.getFileName().toFile().getName();
                String text = mainTitle.text();
                titleStrList.add(generateXml(true, filename, id, text));
                Elements titles = document.getElementsByClass(SUB_TITLE_CLASS);
                int i = 0;
                for (Element title : titles) {
                    String idContent = String.format("child-title-%d", ++i);
                    title.attr("id", idContent);
                    titleStrList.add(generateXml(false, filename, idContent, title.text()));
                }
                titleStrList.add("</navPoint>");
                Files.write(html, document.html().getBytes(StandardCharsets.UTF_8));
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        System.out.println(String.join(StringUtils.EMPTY, titleStrList));
    }

    private String generateXml(boolean isParent, String file, String id, String text) {

        String xml = "<navPoint id=\"num_9\" playOrder=\"9\"> <navLabel><text>%s</text></navLabel><content src=\"text/%s#%s\"/></navPoint>";
        if (isParent) {
            xml = "<navPoint id=\"num_9\" playOrder=\"9\"> <navLabel><text>%s</text></navLabel><content src=\"text/%s#%s\"/>";
        }
        return String.format(xml, text, file, id);
    }
}
